// 云函数入口文件
const cloud = require('wx-server-sdk')
const env = 'bbq-6gz7knah1c296b0f'
cloud.init(env)

const db = cloud.database({ env })

// 云函数入口函数
exports.main = async (event, context) => {
  console.log(event);
  //删除文章
  if (event.code == 0) {
    const file = []
    //删除文章评论
    await db.collection('comments').where({
      articleId:event.articleId
    }).remove()
    //删除收藏
    await db.collection('users').where({
      stores:db.command.in([event.articleId])
    }).update({
      data:{
        stores:db.command.pull(event.articleId),
        praises:db.command.pull(event.articleId)
      }
    })

    //删除文章图片
    await db.collection('articles').where({
      _id:event.articleId
    }).get().then(res=>{
      // console.log(res.data[0].fileList);
      res.data[0].fileList.forEach(element => {
        file.push(element.url)
      });
      console.log(file);
    })
    //删除文章
    await db.collection('articles').where({
      _id:event.articleId
    }).remove()
    return file
  }

  //删除评论
  else if(event.code == 1){
    arc = {}
    //找到文章数据
    await db.collection('comments').where({
      _id:event.commentId
    }).get().then(res=>{
      arc = res.data[0]
    })
    // console.log(arc);
    //修改文章评论数
    if(arc){
      await db.collection('articles').doc(arc.articleId).update({
        data:{
          commentCount:db.command.inc(-1)
        }
      })
      //删除评论
      await db.collection('comments').where({
        _id:event.commentId
      }).remove()
      //返回新评论数组
      return await db.collection('comments').where({
        commentUserId:arc.commentUserId
      }).get()
    }
  }
  //删除收藏
  else if(event.code == 2){
    // console.log(event);
    //删除user的收藏
    await db.collection('users').where({
      _id:event.userId
    })
    .update({
      stores:db.command.pull(event.articleId)
    })
    删除article的收藏
    await db.collection('articles').where({
      _id:event.articleId
    }).update({
      stores:db.command.pull(event.userId)
    })

    const data = await db.collection('users').where({
      _id:event.userId
    }).get()
    return await db.collection('articles').aggregate()
    .lookup({
      from:'users',
      localField:'authorId',
      foreignField:'userId',
      as:'articletWithuser'
    }).match({
      _id:db.command.in(data.list[0].stores)
    }).end()
  }
}